package com.pur.zsms.ordercustommanage.web;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.common.util.PubFun;
import com.pur.zsms.foodmanage.food.po.FoodMaterPo;
import com.pur.zsms.foodmanage.food.vo.FoodVo;
import com.pur.zsms.matermanage.mater.po.MaterLevelPo;
import com.pur.zsms.matermanage.mater.po.MaterPo;
import com.pur.zsms.matermanage.mater.service.IMaterService;
import com.pur.zsms.matermanage.mater.vo.MaterVo;
import com.pur.zsms.ordercustommanage.po.OrderCustPo;
import com.pur.zsms.ordercustommanage.po.OrderSupplierMaterPo;
import com.pur.zsms.ordercustommanage.po.OrderSupplierPo;
import com.pur.zsms.ordercustommanage.service.ICustMaterDetailedOrderService;
import com.pur.zsms.ordercustommanage.service.ICustMaterOrderService;
import com.pur.zsms.ordercustommanage.service.ISelectFoodService;
import com.pur.zsms.ordercustommanage.service.InsertCusFoodService;
import com.pur.zsms.ordercustommanage.service.impl.CustMaterOrderServiceImpl;
import com.pur.zsms.ordercustommanage.vo.OrderCustFoodVo;
import com.pur.zsms.ordercustommanage.vo.OrderCustVo;
import com.pur.zsms.ordercustommanage.vo.OrderStateVo;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierMaterRealVo;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierMaterVo;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierVo;
import com.pur.zsms.ordercustommanage.vo.SelectFoodList;
import com.pur.zsms.ordercustommanage.vo.SelectFoodVo;
import com.pur.zsms.ordercustommanage.vo.SelectMaterVo;
import com.pur.zsms.ordercustommanage.vo.ExcelVo;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.service.IUserService;
import com.pur.zsms.shopmanage.service.IShopService;
import com.pur.zsms.storemanage.service.IStoreService;
import com.pur.zsms.storemanage.vo.StoreInVo;
import com.pur.zsms.storemanage.vo.StoreMaterVo;
import com.pur.zsms.storemanage.vo.StoreOutVo;
import com.pur.zsms.supplier.po.ShopSupplierTypePo;
import com.pur.zsms.supplier.service.ISupplierOrderService;
import com.pur.zsms.supplier.service.ISupplierService;
import com.pur.zsms.timecontrol.service.ITimeControlService;
import com.pur.zsms.unusual.service.IUnusualService;

@Controller
@RequestMapping(value = "/orderSelf")
public class OrderCustSelfControllor {

	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(OrderCustSelfControllor.class);

	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "selectFoodService")
	private ISelectFoodService selectFoodService;

	@Resource(name = "insertCusFoodService")
	private InsertCusFoodService insertCusFoodService;

	@Resource(name = "custMaterOrderService")
	private ICustMaterOrderService custMaterOrderService;

	@Resource(name = "custMaterDetailedOrderService")
	private ICustMaterDetailedOrderService custMaterDetailedOrderService;

	@Resource(name = "supplierService")
	private ISupplierService supplierService;

	@Resource(name = "supplierOrderService")
	private ISupplierOrderService supplierOrderService;

	@Resource(name = "unusualService")
	private IUnusualService unusualService;

	@Resource(name = "storeService")
	private IStoreService storeService;

	@Resource(name = "timeControlService")
	private ITimeControlService timeControlService;

	@Resource(name = "materService")
	private IMaterService materService;

	@Resource(name = "shopService")
	private IShopService shopService;

	/**
	 * 选择材料 自采
	 * */
	@RequestMapping(value = "/commitMaterOrderSelf.do", method = { RequestMethod.POST })
	@ResponseBody
	public String commitMaterOrderSelf(SelectMaterVo selectMaterVo, HttpSession session) {

		JSONObject json1 = new JSONObject();

		UserPo userInfo = (UserPo) session.getAttribute("user");
		try {
			long shopId = shopService.getShopIdoByUserId(userInfo.getUserId());

			// 增加校验 每天只能提交一次采购清单-----------下
			int ordId = selectFoodService.checkCommitMaterOrder(selectMaterVo.getOrderDate(), shopId, 1);
			if (ordId != 0) {
				json1.put("success", false);
				json1.put("msg", selectFoodService.getMsg());
				return json1.toString();
			}
			// 增加校验 每天只能提交一次采购清单-----------上

			// 根据日期取得星期几-----------下
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date date = null;
			date = format.parse(selectMaterVo.getOrderDate());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			if (dayOfWeek < 0)
				dayOfWeek = 0;
			selectMaterVo.setOrderDay(dayNames[dayOfWeek]);
			// 根据日期取得星期几-----------上
			JSONArray array = JSONArray.fromObject(selectMaterVo.getMaterdategridList());

			List<SelectMaterVo> arraylistForReal = new ArrayList<SelectMaterVo>();

			List<SelectMaterVo> selectMaterVoList = new ArrayList<SelectMaterVo>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject object = JSONObject.fromObject(array.get(i));
				SelectMaterVo tselectMaterVo = new SelectMaterVo();
				tselectMaterVo.setMaterId(Integer.valueOf(object.get("materId").toString()));
				tselectMaterVo.setMaterNum(new BigDecimal(object.get("materNum").toString()));
				tselectMaterVo.setMaterValueUndressed(new BigDecimal(object.get("materValueUndressed").toString()).divide(
						new BigDecimal(object.get("materNum").toString()), 2, BigDecimal.ROUND_HALF_UP));
				tselectMaterVo.setMaterLevel(Integer.valueOf(object.get("materLevel").toString()));
				tselectMaterVo.setOrderDate(selectMaterVo.getOrderDate());
				tselectMaterVo.setOrderDay(selectMaterVo.getOrderDay());

				selectMaterVoList.add(tselectMaterVo);

				// 把json封装下面会继续用

				SelectMaterVo tselectMaterVo2 = new SelectMaterVo();

				tselectMaterVo2.setMaterId(Integer.valueOf(object.get("materId").toString()));
				tselectMaterVo2.setMaterNum(new BigDecimal(object.get("materNum").toString()));
				tselectMaterVo2.setMaterValueUndressed(new BigDecimal(object.get("materValueUndressed").toString()).divide(
						new BigDecimal(object.get("materNum").toString()), 2, BigDecimal.ROUND_HALF_UP));
				tselectMaterVo2.setMaterLevel(Integer.valueOf(object.get("materLevel").toString()));
				tselectMaterVo2.setMaterValueAll(new BigDecimal(object.get("materValueUndressed").toString()));
				arraylistForReal.add(tselectMaterVo2);

			}

			// 往客户订单表中插入值
			ordId = selectFoodService.addMaterOrderForSelf(selectMaterVoList, shopId);
			insertCusFoodService.addMaterOrderFoodForSelfForunusual(selectMaterVoList, userInfo, ordId);
			// 往供应商订单表中插入值

			// 取得订单主表实体对象
			OrderCustVo orderCustVo = new OrderCustVo();
			orderCustVo = selectFoodService.getOrderCust(String.valueOf(ordId));
			List<OrderCustFoodVo> orderCustFoodVoList = null;
			orderCustFoodVoList = selectFoodService.getOrderCustFood(String.valueOf(ordId));
			for (int i = 0; i < orderCustFoodVoList.size(); i++) {

				OrderSupplierMaterPo orderSupplierMaterPo = new OrderSupplierMaterPo();
				orderSupplierMaterPo.setOrdId(ordId);
				orderSupplierMaterPo.setOrdFoodId(0);
				orderSupplierMaterPo.setOrdMaterId(orderCustFoodVoList.get(i).getOrdMaterId());

				// 食材 价格 重量信息

				orderSupplierMaterPo.setOrdMaterWeight(orderCustFoodVoList.get(i).getOrdMaterNum());
				orderSupplierMaterPo.setOrdMaterValue(orderCustFoodVoList.get(i).getOrdMaterValue());

				// 供货商为0 为自采
				orderSupplierMaterPo.setOrdSupId(0);

				orderSupplierMaterPo.setOrdMaterLevel(orderCustFoodVoList.get(i).getOrdMaterLevel());
				// 插入供货生附表信息
				selectFoodService.addOrderSupplierMater(orderSupplierMaterPo);
				// }
			}

			// ----生成材料订单的主表---
			List<Object[]> list = selectFoodService.getOrderSupplierMaterByOrdId(String.valueOf(ordId));
			for (int i = 0; i < list.size(); i++) {
				OrderSupplierPo orderSupplierPo = new OrderSupplierPo();
				orderSupplierPo.setOrdCustId(orderCustVo.getOrdCustId());
				orderSupplierPo.setOrdDate(orderCustVo.getOrdDate());
				orderSupplierPo.setOrdDay(orderCustVo.getOrdDay());
				orderSupplierPo.setOrdId(orderCustVo.getOrdId());
				orderSupplierPo.setOrdState(5);// 收货
				orderSupplierPo.setOrdPaymentState(2);// 正常结款状态
				orderSupplierPo.setCommitDeliverState(1);// 提交实际送货重量的状态 未提交

				Object[] a = list.get(i);
				orderSupplierPo.setOrdSupId(Integer.valueOf(a[0].toString()));
				orderSupplierPo.setOrdValue(new BigDecimal(a[1].toString()));
				orderSupplierPo.setOrdValueReal(new BigDecimal(a[1].toString()));
				selectFoodService.addOrderSupplier(orderSupplierPo);

			}

			// 插入到真实需要的表中
			// String ordSupId = "";
			List<OrderSupplierMaterRealVo> orderSupplierMaterRealVoList = new ArrayList<OrderSupplierMaterRealVo>();
			for (int i = 0; i < arraylistForReal.size(); i++) {
				OrderSupplierMaterRealVo tOrderSupplierMaterRealVo = new OrderSupplierMaterRealVo();
				tOrderSupplierMaterRealVo.setOrdMaterId(arraylistForReal.get(i).getMaterId());
				// 设定实际重量
				tOrderSupplierMaterRealVo.setOrdMaterWeightReal(arraylistForReal.get(i).getMaterNum());

				// 直接选择材料不设置 需要重量表 ，因为不会自动产生出库订单
				/*
				 * // 需要的重量 tOrderSupplierMaterRealVo .setOrdMaterWeight(new
				 * BigDecimal(object.get("materNum").toString()));
				 */

				tOrderSupplierMaterRealVo.setOrdMaterLevel(Integer.valueOf(arraylistForReal.get(i).getMaterLevel()));
				// 供货商
				tOrderSupplierMaterRealVo.setOrdSupId(0);
				// ordSupId = object.get("supId").toString();
				// 订单id
				tOrderSupplierMaterRealVo.setOrdId(ordId);
				// 订单价格
				tOrderSupplierMaterRealVo.setOrdMaterValueUnit(arraylistForReal.get(i).getMaterValueUndressed());
				tOrderSupplierMaterRealVo.setOrdMaterValue(arraylistForReal.get(i).getMaterValueAll());
				tOrderSupplierMaterRealVo.setOrdCustId((int) userInfo.getUserId());
				tOrderSupplierMaterRealVo.setCheckflag(true);
				orderSupplierMaterRealVoList.add(tOrderSupplierMaterRealVo);

			}

			// 插入到材料真实进货表中
			boolean flag = selectFoodService.addOrderSupplierMaterRealForSelf(orderSupplierMaterRealVoList);
			/*
			 * if (flag) { OrderSupplierPo orderSupplierPo = new
			 * OrderSupplierPo(); orderSupplierPo =
			 * supplierOrderService.getOrderSupByOrdIdSupId(ordId, ordSupId);
			 * supplierOrderService.updateOrderSupPoState(orderSupplierPo, 3);
			 * json1.put("success", true); } else { json1.put("success", false);
			 * json1.put("msg", selectFoodService.getMsg()); return
			 * json1.toString(); }
			 */

			// 删除购物车中的商品
			materService.deleteShoppingCartForCustSelf(shopId);
			json1.put("success", true);
		} catch (Exception e) {
			log.info(e.toString());
			json1.put("success", false);
			json1.put("msg", e.getMessage());
		}
		return json1.toString();
	}

	/**
	 * 选择材料
	 * */
	@RequestMapping(value = "/commitMaterOrderForUpdate.do", method = { RequestMethod.POST })
	@ResponseBody
	public String commitMaterOrderForUpdate(SelectMaterVo selectMaterVo, HttpSession session) {

		JSONObject json1 = new JSONObject();

		UserPo userInfo = (UserPo) session.getAttribute("user");
		try {
			long shopId = shopService.getShopIdoByUserId(userInfo.getUserId());
			// 增加对时间的校验
			boolean flagTime = false;

			JSONArray array = JSONArray.fromObject(selectMaterVo.getMaterdategridList());
			List<OrderSupplierMaterRealVo> orderSupplierMaterRealVoList = new ArrayList<OrderSupplierMaterRealVo>();
			List<SelectMaterVo> selectMaterVoList = new ArrayList<SelectMaterVo>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject object = JSONObject.fromObject(array.get(i));
				SelectMaterVo tselectMaterVo = new SelectMaterVo();
				tselectMaterVo.setMaterId(Integer.valueOf(object.get("materId").toString()));
				tselectMaterVo.setMaterNum(new BigDecimal(object.get("materNum").toString()));
				tselectMaterVo.setMaterValueUndressed(new BigDecimal(object.get("materValueUndressed").toString()));
				tselectMaterVo.setMaterLevel(Integer.valueOf(object.get("materLevel").toString()));
				tselectMaterVo.setOrderDate(selectMaterVo.getOrderDate());
				tselectMaterVo.setOrderDay(selectMaterVo.getOrderDay());
				tselectMaterVo.setMaterValueAll(tselectMaterVo.getMaterNum().multiply(tselectMaterVo.getMaterValueUndressed()));
				selectMaterVoList.add(tselectMaterVo);

				// 把json封装下面会继续用
				OrderSupplierMaterRealVo tOrderSupplierMaterRealVo = new OrderSupplierMaterRealVo();
				tOrderSupplierMaterRealVo.setOrdMaterId(Integer.valueOf(object.get("materId").toString()));
				tOrderSupplierMaterRealVo.setOrdMaterWeightReal(new BigDecimal(object.get("materNum").toString()));
				tOrderSupplierMaterRealVo.setOrdMaterLevel(Integer.valueOf(object.get("materLevel").toString()));
				tOrderSupplierMaterRealVo.setOrdMaterValueUnit(new BigDecimal(object.get("materValueUndressed").toString()));
				tOrderSupplierMaterRealVo.setOrdSupId(0);
				tOrderSupplierMaterRealVo.setOrdId(Integer.valueOf(object.get("ordId").toString()));
				tOrderSupplierMaterRealVo.setOrdCustId((int) shopId);
				tOrderSupplierMaterRealVo.setCheckflag(true);
				orderSupplierMaterRealVoList.add(tOrderSupplierMaterRealVo);

			}

			// 往客户订单表中插入值
			insertCusFoodService.updateMaterOrderFoodForSelf(selectMaterVoList, selectMaterVo.getOrdId());
			selectFoodService.updateMaterOrderForSelf(selectMaterVo.getOrdId());

			// 删除供货商订单
			selectFoodService.deleteSupOrderByOid(selectMaterVo.getOrdId());

			// 往供应商订单表中插入值

			// 取得订单主表实体对象
			OrderCustVo orderCustVo = new OrderCustVo();
			orderCustVo = selectFoodService.getOrderCust(String.valueOf(selectMaterVo.getOrdId()));
			/*
			 * List<OrderCustFoodVo> orderCustFoodVoList = null;
			 * orderCustFoodVoList = selectFoodService
			 * .getOrderCustFood(String.valueOf(selectMaterVo.getOrdId()));
			 */
			for (int i = 0; i < selectMaterVoList.size(); i++) {

				OrderSupplierMaterPo orderSupplierMaterPo = new OrderSupplierMaterPo();

				List<OrderSupplierMaterPo> tOrderSupplierMaterPoList = selectFoodService.getOrderSupplierMaterPoByMateridOrdId(
						selectMaterVoList.get(i).getMaterId(), selectMaterVo.getOrdId());
				if (tOrderSupplierMaterPoList != null && tOrderSupplierMaterPoList.size() > 0) {
					orderSupplierMaterPo = tOrderSupplierMaterPoList.get(0);
					orderSupplierMaterPo.setOrdMaterWeight(selectMaterVoList.get(i).getMaterNum().add(orderSupplierMaterPo.getOrdMaterWeight()));
					orderSupplierMaterPo.setOrdMaterValue(orderSupplierMaterPo.getOrdMaterWeight().multiply(
							selectMaterVoList.get(i).getMaterValueUndressed()));
				} else {
					orderSupplierMaterPo.setOrdId(selectMaterVo.getOrdId());
					orderSupplierMaterPo.setOrdFoodId(0);
					orderSupplierMaterPo.setOrdMaterId(selectMaterVoList.get(i).getMaterId());

					// 食材 价格 重量信息

					orderSupplierMaterPo.setOrdMaterWeight(selectMaterVoList.get(i).getMaterNum());
					orderSupplierMaterPo.setOrdMaterValue(orderSupplierMaterPo.getOrdMaterWeight().multiply(
							selectMaterVoList.get(i).getMaterValueUndressed()));
					orderSupplierMaterPo.setOrdSupId(selectMaterVoList.get(i).getSupId());
					orderSupplierMaterPo.setOrdMaterLevel(1);
				}
				// 插入供货生附表信息
				selectFoodService.updateOrderSupplierMater(orderSupplierMaterPo);
				// }
			}
			// 周子意
			// ----生成材料订单的主表---
			List<Object[]> list = selectFoodService.getOrderSupplierMaterByOrdId(String.valueOf(selectMaterVo.getOrdId()));
			for (int i = 0; i < list.size(); i++) {
				OrderSupplierPo orderSupplierPo = new OrderSupplierPo();
				orderSupplierPo.setOrdCustId(orderCustVo.getOrdCustId());
				orderSupplierPo.setOrdDate(orderCustVo.getOrdDate());
				orderSupplierPo.setOrdDay(orderCustVo.getOrdDay());
				orderSupplierPo.setOrdId(orderCustVo.getOrdId());
				orderSupplierPo.setOrdState(3);
				Object[] a = list.get(i);
				orderSupplierPo.setOrdSupId(Integer.valueOf(a[0].toString()));
				orderSupplierPo.setOrdValue(new BigDecimal(a[1].toString()));
				selectFoodService.updateOrderSupplier(orderSupplierPo);

			}
			// 插入到材料真实进货表中
			boolean flag = selectFoodService.addOrderSupplierMaterRealForSelfUpdate(orderSupplierMaterRealVoList);

			// 删除购物车中的商品
			materService.deleteShoppingCartForCustSelf(shopId);
			json1.put("success", true);
		} catch (Exception e) {
			log.info(e.toString());
			json1.put("success", false);
			json1.put("msg", e.getMessage());
		}
		return json1.toString();
	}
}
